#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2025/10/24 22:49
# @Author  : summer
# @Email   : 610658552@qq.com
# @File    : tool_wechat.py
# @Software: PyCharm
# @Desc    : 发送微信公众号消息
# https://mp.weixin.qq.com/debug/cgi-bin/sandbox?t=sandbox/login
import requests
import json
import time


class WeChatMessageSender:
    def __init__(self, appid, appsecret):
        self.appid = appid
        self.appsecret = appsecret
        self.access_token = None
        self.token_expire_time = 0

    def _get_access_token(self):
        """获取微信access_token（有效期2小时）"""
        if time.time() < self.token_expire_time and self.access_token:
            return self.access_token

        url = f"https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={self.appid}&secret={self.appsecret}"
        response = requests.get(url).json()

        if 'access_token' in response:
            self.access_token = response['access_token']
            self.token_expire_time = time.time() + 7200  # 2小时有效期
            return self.access_token
        else:
            raise Exception(f"获取access_token失败: {response}")

    def send_template_message(self, openid, template_id, data, url=None):
        """发送模板消息"""
        access_token = self._get_access_token()
        api_url = f"https://api.weixin.qq.com/cgi-bin/message/template/send?access_token={access_token}"

        payload = {
            "touser": openid,
            "template_id": template_id,
            "data": data
        }
        if url:
            payload["url"] = url  # 可选：用户点击消息跳转的链接

        response = requests.post(api_url, json=payload)
        result = response.json()

        if result.get('errcode') == 0:
            print("消息发送成功！")
            return True
        else:
            print(f"消息发送失败: {result}")
            return False


# 使用示例
if __name__ == "__main__":
    # 配置微信公众号信息
    WXAPPID = "wxa36512f44bdbc221"
    WXAPPSECRET = "b04c124212766f8c419a3241ca94f143"

    # 初始化发送器
    sender = WeChatMessageSender(WXAPPID, WXAPPSECRET)

    # 消息模板数据（根据你的模板字段调整）
    # openid = "o52C55jQ_xeZy04VxREWM3zg6S9Y"
    # phone = "19045131668"
    # current_time = time.strftime("%Y年%m月%d日 %H:%M:%S", time.localtime())
    # template_id = "jnoo3mgI5rL0Ehk3DRowsYcn6ifunojuSr8AGIoMzb8"  # 注册
    # json_data = {
    #     "phone_number1": {"value": "%s" % phone},  # 正确格式：嵌套value
    #     "time3": {"value": current_time},
    #     "remark": {"value": "remark"}
    # }

    # ---- 注册
    # openid = "o52C55jQ_xeZy04VxREWM3zg6S9Y"
    # phone = "19045131668"
    # current_time = time.strftime("%Y年%m月%d日 %H:%M:%S", time.localtime())
    # template_id = "bWa4vCfRo_JxxQy41V8bMUs8PY94trXimES340JykOM"  # 注册
    # password = "xxxxx"
    # json_data = {
    #     "phone_number3": {"value": "%s" % phone},  # 正确格式：嵌套value
    #     "time8": {"value": current_time},
    #     "thing11": {"value": "注册成功"},
    #     "character_string4": {"value": password},
    #     "remark": {"value": "remark"}
    # }

    # 绑定活动
    openid = "o52C55jQ_xeZy04VxREWM3zg6S9Y"
    phone = "19045131668"
    current_time = time.strftime("%Y年%m月%d日 %H:%M:%S", time.localtime())
    template_id = "bWa4vCfRo_JxxQy41V8bMSODiPTeegbP9BAMyYmtU8A"  # 绑定
    json_data = {
        "phone_number3": {"value": "%s" % phone},  # 正确格式：嵌套value
        "time8": {"value": current_time},
        "thing11": {"value": "绑定成功"},
        "remark": {"value": "remark"}
    }

    # template_id = "HzvBOeBKgqSDi_jfvyFt_O5SyP7Sv3_whbAlR7qukX0" # 咨询
    # json_data = {
    #     # 手机号
    #     "phone_number9": {"value": phone},
    #     # 门店名称
    #     "thing1": {"value": "门店名称"},
    #     # 咨询类型
    #     "thing11": {"value": "咨询类型"},
    #     # 活动ID
    #     "thing7": {"value": "活动ID"},
    #     # 提交时间
    #     "time4": {"value": current_time}
    # }
    # template_id = "jnoo3mgI5rL0Ehk3DRowsfBs4zKyJBSmqd8BUq8Y-lk"  # 注册
    # json_data = {
    #     "phone_number1": {"value": "%s" % phone},  # 正确格式：嵌套value
    #     "time3": {"value": current_time},
    #     "const22": {"value": "创建活动"}
    # }
    # 发送消息
    sender.send_template_message(
        openid=openid,
        template_id=template_id,
        data=json_data,
        # url="https://www.jd.com"  # 可选：跳转链接
    )
